'use strict';
/**
 * 角色管理服务类
 */
const Service = require('egg').Service;
class RoleService extends Service {

  /**
   * 分页查询
   * @param page 页数 
   */
  async getRolePageList(page) {
    const { ctx } = this;
    //每页数量
    let pageSize = 8;
    let query = { offset: (page - 1) * pageSize, limit: pageSize, order: [['id', 'desc']] };
    let count = await ctx.model.Role.count();
    let result = await ctx.model.Role.findAll(query)
    // let totalPages = Math.ceil(count / pageSize);
    let pageList = {
      list: result,
      pageSize: pageSize,
      page: page,
      total: count
    };
    return pageList;
  }

  /**
   * 新建
   * @param name 名称
   * 
   */
  async saveRole({ id, name }) {
    const { ctx, logger } = this;
    let result = null;
    if (id != 'undefined' && id != null) {
      let role = await ctx.model.Role.findById(id);
      if (!role) {
        return false;
      }
      result = await role.update({ name: name });
    } else {
      result = await ctx.model.Role.create({ name: name });
    }

    if (!result) {
      return false;
    }
    logger.info('***role***返回结果->{}******', result);
    return result;
  }

  /**
   * 删除
   * @param id  
   */
  async deleteRole(id) {
    const { ctx } = this;
    let role = await ctx.model.Role.findById(id);
    if (!role) {
      return false;
    }
    let result = await role.destroy();
    return result;
  }

  /**
   * 列表
   */
  async getRoleList(){
    const {ctx} = this;
    let roles = await ctx.model.Role.findAll();
    if(!roles){
      return false;
    }
    return roles;
  }

  /**
   * 根据角色ID获得对应的权限
   * @param id 
   */
  async getPermissionByRoleId(id){
    const {ctx} = this;
    let permissions = await ctx.model.RoleAccess.findOne({where: {role_id:id}})
    if(!permissions){
      return false;
    }
    return permissions.access_id.split(',');//把字符串变成数组
  }

  /**
   * 根据角色id保存新的用户权限
   * @param id 
   * @param newPermissions
   */
  async saveNewPermissionsByRoleId({ newPermissions,id}){
    const {ctx} = this;
    let access = await ctx.model.RoleAccess.findOne({where: {role_id:id}});
    if(!access){
      return false;
    }

    let newAccess = newPermissions.join(',');//把数组变成字符串
    let result = access.update({ access_id: newAccess })
    return result;
  }
}

module.exports = RoleService;
